﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Ideal.API.LinqTextQueryBuilder;
using System.Reflection;
using System.Collections;

namespace test
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        LinqTextQueryBuilder queryBuilder;

        public MainWindow()
        {
            InitializeComponent();
            queryBuilder = new LinqTextQueryBuilder( "test" );
            QueryText.Text = "from TestEntity e in source\n" +
                             "where e.Age > 14\n" +
                             "select new { e.Name, e.Age }";
            GenerateSource();
        }

        public void GenerateSource()
        {
            var source = TestEntity.Create().ToList();
            queryBuilder.SetSource( source.AsQueryable() );
            SourceGrid.ItemsSource = source;
        }
        public void ShowResult( IList result )
        {
            ResultTab.SelectedIndex = 0;
            ResultGrid.ItemsSource = result;
            ErrorGrid.ItemsSource = null;
        }
        public void ShowError( LinqTextQueryRuntimeException error )
        {
            ResultTab.SelectedIndex = 1;
            ResultGrid.ItemsSource = null;
            ErrorGrid.ItemsSource = error.Errors.ToList();
        }

        private void QueryButton_Click( object sender, RoutedEventArgs e )
        {
            if ( QueryText.Text != string.Empty )
            {
                try
                {
                    var result = queryBuilder.Query( QueryText.Text );
                    ShowResult( result );
                }
                catch ( LinqTextQueryRuntimeException exp )
                {
                    ShowError( exp );
                }
                catch ( Exception exp )
                {
                    MessageBox.Show( exp.Message );
                }
            }
        }
        private void GenerateNewSourceButton_Click( object sender, RoutedEventArgs e )
        {
            GenerateSource();
        }

    }
}
